package com.bfxy.rabbit.producer.broker;

import com.bfxy.rabbit.api.business.MessageProducer;
import com.bfxy.rabbit.api.business.SendCallback;
import com.bfxy.rabbit.api.enums.MessageTypeEnum;
import com.bfxy.rabbit.api.exception.MessageRunTimeException;
import com.bfxy.rabbit.api.model.Message;
import com.google.common.base.Preconditions;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * $ProducerClient 发送消息的实际实现类
 */
@Component
public class ProducerClient implements MessageProducer {

    @Resource
    private final RabbitBroker rabbitBroker;

    public ProducerClient(RabbitBroker rabbitBroker) {
        this.rabbitBroker = rabbitBroker;
    }

    @Override
    public void send(Message message) throws MessageRunTimeException {
        // 避免不使用MessageBuilder构建的方式（比如直接new Message）导致的topic为空的情况
        Preconditions.checkNotNull(message.getTopic());
        MessageTypeEnum messageType = message.getMessageType();
        switch (messageType) {
            case RAPID:
                rabbitBroker.rapidSend(message);
                break;
            case CONFIRM:
                rabbitBroker.confirmSend(message);
                break;
            case RELIANT:
                rabbitBroker.reliantSend(message);
                break;
            default:
                break;
        }
    }

    @Override
    public void send(List<Message> messageList) throws MessageRunTimeException {
        messageList.forEach(message -> {
            message.setMessageType(MessageTypeEnum.RAPID);
            MessageHolder.add(message);
        });
        rabbitBroker.sendMessages();
    }

    @Override
    public void send(Message message, SendCallback sendCallback) throws MessageRunTimeException {
        // TODO
    }

}
